require.config({
    paths: {
        'columntoggle': '../addons/facrm/js/columntoggle',
    }
});
var index=1;
define(['jquery', 'bootstrap', 'backend', 'table', 'form','columntoggle'], function ($, undefined, Backend, Table, Form,Columntoggle) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/business/index/index',
                    add_url: 'facrm/business/index/add',
                    edit_url: 'facrm/business/index/edit',
                    del_url: 'facrm/business/index/del',
                    multi_url: '',
                    table: '',
                }
            });
            var select = Backend.api.query('select');
            select = select == '1' ? true : false;

            var table = $("#business");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
               
                if (from_type=="need"){
                    //如果是需要跟进的商机
                    $(".commonsearch-table").removeClass("hidden");
                    $("input[name='next_time']").val(Moment().year(Moment().year() -1).startOf('year').format('YYYY-MM-DD H:mm:ss') + ' - ' + Moment().endOf('day').format('YYYY-MM-DD H:mm:ss'));
                }
                $(".commonsearch-table select[name=scene_id]").val(7);
             
            });
            var columnss=   [

                {field: 'id', title: 'ID'},
                {
                    field: 'scene_id',
                    title: __('商机场景'),
                    visible: false,
                    formatter: function (v, r) {
                        return scene_list[v];
                    }, searchList: scene_list
                },
                {
                    field: 'name',
                    title: __('商机名称'),
                    operate: "LIKE",
                    align: 'left',
                    formatter: function (value, row, index) {
                        value='<a href="javascript:void(0);" data-url="facrm/business/index/edit/ids/' + row.id
                            +'" data-area="[&quot;100%&quot;,&quot;100%&quot;]" class="btn-dialog" data-title="'+ row.name+'">'+ row.name+'</a>';
                        return value;
                    }},
                {
                    field: 'customer_id',
                    title: __('客户名称'),
                    align: 'left',
                    formatter: function (value, row, index) {
                        if(!row.customer) return '-';
                        value='<a href="javascript:void(0);" data-url="facrm/customer/index/detail/ids/' + row.customer_id
                            +'" data-area="[&quot;100%&quot;,&quot;100%&quot;]" class="btn-dialog" data-title="'+ row.customer.name+'">'+ row.customer.name+'('+row.customer_id+')'+'</a>';
                        return value;
                    },
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/customer/index?filter=%7B\"scene_id\"%3A\"1\"%7D" data-field="name" data-orderBy="id desc"'},
                {field: 'money', title: __('客户预算'), operate: 'BETWEEN', sortable: true},
                {field: 'total_price', title: __('产品价格'), operate: 'BETWEEN', sortable: true},

                {field: 'remark', title: __('备注'), operate: 'LIKE'},
                {
                    field: 'deal_time',
                    title: __('预计成交'),
                    formatter: Table.api.formatter.datetime,
                    operate: 'RANGE',
                    addclass: 'datetimerange',
                    sortable: true,
					extend: 'autocomplete="off"'
                },
                {
                    field: 'next_time',
                    title: __('下次跟进'),
                    formatter: Table.api.formatter.datetime,
                    operate: 'RANGE',
                    addclass: 'datetimerange',
                    sortable: true,
					extend: 'autocomplete="off"'
                },
                {field: 'create_user_id', title: __('创建人'),addclass: 'selectpage',formatter: function (value, row, index) {
                        if(!row.create_user) return '-';
                        return row.create_user.nickname;
                    },
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname" data-orderBy="id desc"'},
                {field: 'owner_user_id', title: __('负责人'), addclass: 'selectpage',formatter: function (value, row, index) {
                        if(!row.owner_user) return '-';
                        return row.owner_user.nickname;
                    },
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname" data-orderBy="id desc"'},
                {
                    field: 'update_time',
                    title: __('更新时间'),
                    formatter: Table.api.formatter.datetime,
                    operate: 'RANGE',
                    addclass: 'datetimerange',
                    sortable: true,
					extend: 'autocomplete="off"'
                },
                {
                    field: 'is_end',
                    title: __('Status'),
                    formatter: Table.api.formatter.status,
                    searchList: Config.is_end_list
                },
            ]
            if (Config.fields && Object.keys(Config.fields).length > 0) {
                var fields = JSON.parse(Config.fields);
                for (var i = 0; i < fields.length; i++) {
                    if (fields[i].hasOwnProperty('formatter'))
                        fields[i].formatter = eval(fields[i].formatter);
                    if (fields[i].hasOwnProperty('events'))
                        fields[i].events = eval(fields[i].events);

                    columnss.push( fields[i]);
                }
            }
            //追加操作字段
            if (select){
                //如果是选择
                columnss.push( {
                    field: 'operate', title: __('Operate'), events: {
                    'click .btn-chooseone': function (e, value, row, index) {
                        Fast.api.close(row);
                    },
                },
                    formatter: function () {
                        return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                    }
                });
            }else {
                columnss.push(  {
                    field: 'operate',
                    title: __('Operate'),
                    table: table,
                    events: Table.api.events.operate,
                    formatter: Table.api.formatter.operate,
                    buttons: [
                        {
                            name: 'record',
                            text: '跟进',
                            title: function ( row) {
                                return '跟进商机-'+row.name;
                            },
                            icon: 'fa fa-commenting-o',
                            classname: 'btn btn-xs btn-danger btn-addtabs',
                            url: 'facrm/business/record/add',
                        },
                        {
                            name: 'email',
                            text: '@',
                            title: '发送邮件',
                            icon: '',
                            classname: 'btn btn-xs btn-success   btn-click',
                            click: function (data,row) {

                                var that = this;
                                var title = __('发邮件给客户：')+row.customer.name;
                                var url = $(that).attr('href');

                                var data = {types:'business',typesid:row.id,customer_id:row.customer_id};
                                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
                            },
                            url:'facrm/apps/email/send',

                        },
                        {
                            name: 'sms',
                            text: '',
                            title: '发送短息',
                            icon: 'fa fa-envelope-o fa-fw',
                            classname: 'btn btn-xs btn-success   btn-click',
                            click: function (data,row) {
                                var that = this;
                                var title = __('发短息给客户：')+row.customer.name;
                                var url = $(that).attr('href');

                                var data = {types:'business',typesid:row.id,customer_id:row.customer_id};
                                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
                            },
                            url:'facrm/apps/sms/send',

                        },
                    ]
                });
            }


            // 初始化表格
            table.bootstrapTable(
                {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ],
                onLoadSuccess: function () {
                    // 载入成功时执行
                    loadSuccess("business")
                },
                onColumnSwitch: function () {
                    // 切换列时执行columnSwitch方法
                    columnSwitch("business","business_table")
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                searchFormVisible:select?false:true, //打开搜索
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name=" + field + "]").val(value);
                return false;
            });
        },
        add: function () {
            Controller.api.bindevent();

            $(function () {
                setnums();
                $('#myModal').on('hidden.bs.modal', function () {
                    $('#table1').bootstrapTable('destroy');
                });
                $('#modelProduct').on('show.bs.modal', function (e) {
                    // console.log(btn)
                    var btn = $(e.relatedTarget)
                    // console.log(e)
                    Controller.api.getProduct(btn);
                });
                $('#modelProduct').on('hidden.bs.modal', function () {
                    $('#table2').bootstrapTable('destroy');
                });
                //计算费率
                $('#totalMoneys').on('blur', function () {
                    var len = $('#table tr').length;
                    var total = 0;
                    for (var b = 1; b < len - 1; b++) {
                        var str = '#table tr:eq(' + b + ') .subtotal';
                        var a = $(str).text();
                        if (a == "") {
                            a = 0;
                        }
                        a = parseFloat(a);
                        if (a == "NaN" || a == "" || a == undefined) {
                            a = 0;
                        }
                        total += a;
                    }
                    $("#table #allMoney").text(total);
                    var totalMoney=parseFloat($("#totalMoneys").val());
                    totalMoney = totalMoney.toFixed(2);
                    var rate=parseFloat((total-totalMoney)/total*100);
                    if (rate<0){
                        rate=0;
                    }
                    $("#c-rate").val(rate.toFixed(2));
                    $("#money").val(total);
                    $("#totalMoneys").val(totalMoney);
                });


            });



        },
        edit: function () {
            Controller.api.bindevent();
            index = $('#table tr').length - 1;
            $(function () {
                setnums();
                $('#myModal').on('hidden.bs.modal', function () {
                    $('#table1').bootstrapTable('destroy');
                });
                $('#modelProduct').on('show.bs.modal', function (e) {
                    // console.log(btn)
                    var btn = $(e.relatedTarget)
                    // console.log(e)
                    Controller.api.getProduct(btn);
                });
                $('#modelProduct').on('hidden.bs.modal', function () {
                    $('#table2').bootstrapTable('destroy');
                });
                //计算费率
                $('#totalMoneys').on('blur', function () {
                    var len = $('#table tr').length;
                    var total = 0;
                    for (var b = 1; b < len - 1; b++) {
                        var str = '#table tr:eq(' + b + ') .subtotal';
                        var a = $(str).text();
                        if (a == "") {
                            a = 0;
                        }
                        a = parseFloat(a);
                        if (a == "NaN" || a == "" || a == undefined) {
                            a = 0;
                        }
                        total += a;
                    }
                    $("#table #allMoney").text(total);
                    var totalMoney=parseFloat($("#totalMoneys").val());
                    totalMoney = totalMoney.toFixed(2);
                    var rate=parseFloat((total-totalMoney)/total*100);
                    if (rate<0){
                        rate=0;
                    }
                    $("#c-rate").val(rate.toFixed(2));
                    $("#money").val(total);
                    $("#totalMoneys").val(totalMoney);
                });


            });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                if ("undefined" == typeof business_id) {
                    business_id = 0;
                }
                Fast.api.ajax({
                    type: 'GET',
                    url: 'facrm/fields/get_fields_html',
                    data: {source: 'business', 'id': business_id}
                }, function (data) {
                    $("#extend").html(data.html);
                    Form.api.bindevent($("#extend"));
                    return false;
                },function () {
                    return false;
                });
            },
            getProduct: function (btn) {
                Table.api.init({
                    extend: {
                        index_url: 'facrm/product/product/index'
                    }
                });
                var table = $("#table2");

                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url,
                    pk: 'id',
                    sortName: 'id',
                    commonSearch: false,
                    escape: false,
                    columns: [
                        [ {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var _this = btn.parent().parent();
                                    var temp_index=_this.find(".find").data("index");
                                    _this.find(".find").val(row.name);
                                    _this.find("input[name='product["+temp_index+"][product_id]']").val(row.id);
                                    _this.find(".unit").text(row.unit);
                                    _this.find("td:eq(2)").text(row.sku);
                                    _this.find("td:eq(7)").text(row.specification);

                                    _this.find(".unit-price").val(row.price);

                                    _this.find("input[name='product["+temp_index+"][sku]']").val(row.sku);
                                    _this.find("input[name='product["+temp_index+"][specification]']").val(row.specification);
                                    _this.find("input[name='product["+temp_index+"][unit]']").val(row.unit);
                                    _this.find("input[name='product[" + temp_index + "][nums]']").val(1);
                                    if (row.prop != ""&&row.prop !=null) {
                                        var arr = JSON.parse(row.prop);
                                        var str = "";
                                        var temp_str="";
                                        for (var i = 0; i < arr.length; i++) {
                                            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                temp_str += arr[i]['title'] + ":" + arr[i]['value'] + "; |";
                                            }
                                        }
                                        _this.find("td:eq(8)").html(str);
                                        _this.find("input[name='product["+temp_index+"][prop]']").val(temp_str);
                                    }
                                    totalNums( _this.find("input[name='product[" + temp_index + "][nums]']"));
                                    $('#modelProduct').modal('hide');
                                },
                            }, formatter: function (val,row) {
                                if(row.inventory<=0) return '无库存';
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                            {
                                field: 'name',
                                title: __('Name')
                            },
                            {
                                field: 'price',
                                title: __('价格')
                            },
                            {
                                field: 'inventory',
                                title: __('库存')
                            },
                            {
                                field: 'specification',
                                title: __('规格')
                            },
                            {
                                field: 'sku',
                                title: __('编码')
                            },
                            {
                                field: 'prop',
                                title: __('属性'),
                                formatter: function (value, row, index) {
                                    var str = "";
                                    if (row.prop != ""&&row.prop !=null) {
                                        var arr = JSON.parse(row.prop);
                                        for (var i = 0; i < arr.length; i++) {
                                            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                            }
                                        }
                                    }
                                    return str;
                                }
                            },


                        ]
                    ]
                });
                Table.api.bindevent(table);
            }
        }
    };
    return Controller;
});
// 添加
function addRow(data) {

    var name="";
    var product_id="";
    var sku="";
    var specification="";
    var prop="";
    var unit="";
    var nums="";
    var subtotal="";
    var remarks="";
    var price="";
    if (data&&Object.keys(data).length > 0){
        console.log(data);
        name=data.info.name;
        product_id=data.product_id;
        sku=data.info.sku;
        specification=data.info.specification;
        prop=prop_handle(data.info.prop);
        unit=data.info.unit;
        nums=data.nums;
        subtotal=data.subtotal;
        remarks=data.remarks;
        price=data.price;
    }

    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
        '<td> <button type="button" class="btn btn-primary" onclick="addRow()">添加</button><button type="button" class="btn btn-default" onclick="delRow(this)" >删除</button> </td>' +
        '<td>' + len + '</td>' +
        '<td>' + sku + '</td>' +
        '<td><input style="width: 100px" value="'+name+'" data-index="'+index+'" type="text"  class="find productname'+index+'" data-toggle="modal" data-target="#modelProduct" data-rule="">' +
        '<input   type="hidden" name="product['+index+'][product_id]" value="'+product_id+'">' +

        '<td><input style="width: 80px"  type="number" value="'+nums+'" name="product['+index+'][nums]" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
        '<td><input style="width: 80px" type="number" value="'+price+'" data-rule="required;range(0~);" name="product['+index+'][price]" onblur="calMoney(this)"  class="unit-price" >' +
        '<td><textarea rows="1" class="remarks" cols="20" name="product['+index+'][remarks]">'+remarks+'</textarea></td>' +
        '<td>' + specification + '</td>' +
        '<td>' + prop + '</td>' +
        '<td class="unit">' + unit + '</td>' +
        '<input   type="hidden" name="product['+index+'][subtotal]" value="'+subtotal+'"   ></td>' +
        '<td class="subtotal">'+subtotal+'</td>' +
        '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
    $(document).ready(function(){
        $(".productname"+index).trigger("click");
    })
    index++;

}

// 删除
function delRow(obj) {

    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    totalNums(null);
    calTotalMoneys()
    setnums();
}

//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:nth-child(2)').text(i);
    }
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        if (nums == "") {
            nums = 0;
        } else {
            nums = getNumValue(nums);
            if (nums == false || nums < 0) {
                total = false;
                return false;
            }
        }

        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);

        $("#allNums").val(total);
    }
}

function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) { //是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}

// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    var temp_index= $(obj).parent().parent().find(".find").data("index");
    $(obj).parent().parent().find("input[name='product["+temp_index+"][subtotal]']").val(total);
    calTotalMoneys();
}

// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 - rate / 100);
    // var totalMoney = total;
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoneys").val(totalMoney);

}

